package com.dream.banana.notify.recoverer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.support.converter.MessageConverter;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Map;

/**
 * 躲了一辈子雨，雨会不会很难过。
 * </p>
 * Created by zhumenglong on 2017/5/28.
 */
public class CustomMessageRecoverer implements MessageRecoverer {
    private static final Logger logger = LoggerFactory.getLogger(CustomMessageRecoverer.class);
    private MessageConverter messageConverter;

    public void recover(Message message, Throwable cause) {
        Map headers = message.getMessageProperties().getHeaders();
        headers.put("x-exception-stacktrace", this.getStackTraceAsString(cause));
        headers.put("x-exception-message",
                cause.getCause() != null ? cause.getCause().getMessage() : cause.getMessage());
        headers.put("x-original-exchange", message.getMessageProperties().getReceivedExchange());
        headers.put("x-original-routingKey", message.getMessageProperties().getReceivedRoutingKey());
        logger.error("handler msg (" + this.messageConverter.fromMessage(message) + ") err, republish to mq.", cause);
    }

    private String getStackTraceAsString(Throwable cause) {
        StringWriter stringWriter = new StringWriter();
        PrintWriter printWriter = new PrintWriter(stringWriter, true);
        cause.printStackTrace(printWriter);
        return stringWriter.getBuffer().toString();
    }

    public void setMessageConverter(MessageConverter messageConverter) {
        this.messageConverter = messageConverter;
    }
}
